﻿using System;
using System.IO;
using System.Data;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using LEDDataBase;
using LEDHelper;
using System.Windows.Interop;
using System.Windows.Shapes;
namespace LEDManager
{
    /// <summary>
    /// Interaction logic for LED.xaml
    /// </summary>
    public partial class LEDUnit : Window
    {
        private HwndSource m_hwndSource;
        public IntPtr Hwnd;
        string BackGroundBmp = "NO";
        string progID = "";
        int screentyp = LEDAPI.SCREEN_COLOR;
        string fileroot;
        string filepath;
        string filestatus;
        LEDData m_data;
        int dev = -1;
        public DataRow RowLED;
        public DataRow dwLEDStatus;
        DataTable LEDStatus;
        DataSet setLED;
        public string ledkey = "";
        public string system = "000";
        public int ledid = 1;
        string Host = "192.168.0.101";
        string DEVTYPE = "DEVICE_TYPE_UDP";
            byte devid = 1;
        UInt16 port = 6666;
        UInt16 comport = 1;
        int width=128;
        int height = 32;
        int nWidth
        {
            get { 
                return width;
            }
            set {
                width = value;
             }            
        }
        int nHeight
        {
            get
            {
                return height;
            }
            set
            {
                height = value;
            } 
        }
        DataRow dwProg, dwFont, dwClock, dwPicture, dwText, dwLeaf, dwLeafDetail;
        public LEDDataSet lEDDataSet
        {
            get
            {
                return (LEDDataSet)this.FindResource("lEDDataSet");
            }
        }
        CollectionViewSource vwLEDLIST
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwLEDLIST");
            }
        }
        CollectionViewSource vwMASTER
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwMASTER");
            }
        }
        CollectionViewSource vwLEDLOCATION
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwLEDLOCATION");
            }
        }
        public LEDUnit()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(LEDUnit_Loaded);
            this.Unloaded += new RoutedEventHandler(LEDUnit_Unloaded);
        }

        void LEDUnit_Loaded(object sender, RoutedEventArgs e)
        {
            #region====Refresh LED================
            PerformCommand("LED_Query");
            Flow1();
            #endregion
        }

        void LEDUnit_Unloaded(object sender, RoutedEventArgs e)
        {

        }
        ~LEDUnit()
        {
            DumpStatusData();
        }

        public void SetUp(DataRow dwLED)
        {
            try
            {
                fileroot = System.IO.Path.Combine(PathHelper.ApplicationPath, @"Data\LEDList");
                setLED = new DataSet();
                dwLEDStatus = null;
                LEDStatus = lEDDataSet.LEDSTATUS.Clone();

                m_data = new LEDData();
                DataSet setResult = new DataSet();
                m_data.Reset();
                lEDDataSet.Merge(m_data.LEDDatas);
                #region=======RowLED=============
                RowLED = dwLED;
                ledkey = RowLED["LLSYSTEM"].ToString() + RowLED["LLLEDID"].ToString().Trim();
                system = RowLED["LLSYSTEM"].ToString();
                DEVTYPE = RowLED["DEVTYPE"].ToString();
                ledid = System.Convert.ToInt16(RowLED["LLLEDID"].ToString().Trim());
                Host = RowLED["IPADDRESS"].ToString();
                port = System.Convert.ToUInt16(RowLED["REMOTPORT"].ToString());
                comport = System.Convert.ToUInt16(RowLED["COMPORT"].ToString());

                string sctype = RowLED["LLSCREENTYPE"].ToString();
                switch (sctype)
                {
                    case "SCREEN_UNICOLOR":
                        screentyp = LEDAPI.SCREEN_UNICOLOR;
                        break;
                    case "SCREEN_COLOR":
                        screentyp = LEDAPI.SCREEN_COLOR;
                        break;
                    case "SCREEN_FULLCOLOR":
                        screentyp = LEDAPI.SCREEN_FULLCOLOR;
                        break;
                    case "SCREEN_GRAY":
                        screentyp = LEDAPI.SCREEN_GRAY;
                        break;
                    default:
                        screentyp = LEDAPI.SCREEN_COLOR;
                        break;
                }

                #endregion
                #region========LEDStatus==========
                LoadStatusData();
                foreach (DataRow dwTemp in LEDStatus.Rows)
                {
                    dwLEDStatus = dwTemp;
                }

                if (dwLEDStatus == null)
                {
                    foreach (DataRow dwTemp in lEDDataSet.LEDSTATUS.Rows)
                    { 
                        string keyx = dwTemp["STSYSTEM"].ToString() + dwTemp["STLEDID"].ToString().Trim();
                        if (keyx == ledkey)
                        {
                            dwLEDStatus = dwTemp;
                        }
                    }
                }
                if (dwLEDStatus == null)
                {
                    dwLEDStatus = LEDStatus.Rows.Add();
                    dwLEDStatus["STSYSTEM"] = RowLED["LLSYSTEM"].ToString();
                    dwLEDStatus["STLEDID"] = RowLED["LLLEDID"].ToString();
                    dwLEDStatus["STPOWER"] = "0";
                    dwLEDStatus["STCURRENTTIME"] = DateTime.Now.ToFileTime();
                    dwLEDStatus["STRUN"] = "0";
                    dwLEDStatus["STBRIGHT"] = 7;
                    dwLEDStatus["STBGBMP"] = "NO";
                    dwLEDStatus["STFREESPACE"] = 204800;
                }
                BackGroundBmp = dwLEDStatus["STBGBMP"].ToString();
                #endregion
                if (dev < 0)
                {
                    PDeviceParam param = new PDeviceParam();
                    if (DEVTYPE == "DEVICE_TYPE_COM")
                    {
                        param.devType = LEDAPI.DEVICE_TYPE_COM;
                        param.ComPort = 3;
                        param.Speed = LEDAPI.SBR_57600;
                        param.FlowCon = 0;
                    } 
                    if (DEVTYPE == "DEVICE_TYPE_UDP")
                    {
                        param.devType = LEDAPI.DEVICE_TYPE_UDP;
                        param.ComPort = 4;
                        param.Speed = LEDAPI.SBR_57600;
                        param.FlowCon = 0;
                    }
                    if (DEVTYPE == "DEVICE_TYPE_485")
                    {
                        param.devType = LEDAPI.DEVICE_TYPE_485;
                        param.ComPort = 3;
                        param.Speed = LEDAPI.SBR_57600;
                        param.FlowCon = 0;
                    } 
                    int Notify = 1;
                    dev = LED_Open(ref param, Notify, (int)Hwnd, LEDAPI.WM_LED_NOTIFY);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void Flow1()
        {
            return;
            int devx = 0;
            PDeviceParam param = new PDeviceParam();
            param.devType = LEDAPI.DEVICE_TYPE_UDP;
            param.ComPort = 4;
            param.Speed = LEDAPI.SBR_57600;
            param.FlowCon = 0;
            devx = LED_Open(ref param, 1, (int)Hwnd, LEDAPI.WM_LED_NOTIFY);

            #region 增加一个节目
            MakeRoot(LEDAPI.ROOT_PLAY, LEDAPI.SCREEN_COLOR);
            #endregion

            AddLeaf(1000);
            IntPtr screenDC = GetDC(IntPtr.Zero);
            IntPtr memDC = CreateCompatibleDC(screenDC);
            Bitmap bmp = new Bitmap(@"D:\SXDFile\A2.jpg");
            IntPtr hBitmap = bmp.GetHbitmap();
            hBitmap = bmp.GetHbitmap();
            SelectObject(memDC, hBitmap); // Select bitmap from compatible bitmap to memDC 
            SRECT srect = new SRECT();
            SetRect(ref srect, 0, 0, 280, 32);
            AddWindow(memDC, 280, 32, ref srect, 1, 1, 1);
            DeleteObject(hBitmap);
            ReleaseDC(IntPtr.Zero, screenDC);
            ReleaseDC(IntPtr.Zero, memDC);
            LED_SendToScreen(devx, 1, "192.168.0.101", 6666);  //发送到1组1号显示屏，此处需要根据现场情况修改
            return;
            #region 初始化设备

            #endregion
            #region 增加一个节目
            MakeRoot(LEDAPI.ROOT_PLAY, LEDAPI.SCREEN_COLOR);
            #endregion
            #region 增加一个帧
            AddLeaf(1000);
            #endregion

            #region 增加一个图片

            string szText = "佛说宇宙人生真相 大道本源西方金  宇宙大母 南无大日如来";
            LEDBlock rect = new LEDBlock();
            rect.nStartX = 0;
            rect.nStartY = 0;
            rect.nWidth = 128;
            rect.nHeight = 32;

            SRECT rectx = new SRECT();
            rectx.left = rect.nStartX;
            rectx.top = rect.nStartY;
            rectx.right = rect.nStartX + rect.nWidth;
            rectx.bottom = rect.nStartY + rect.nHeight;

            string fontname = "楷书";

            AddText(szText, ref rectx, 1, 1, 1, fontname, 16, 234);

            #endregion
            //ReleaseDC(hdc, IntPtr.Zero);
            #region 发送到设备
            LED_SendToScreen(devx, 1, "192.168.0.101", 6666);  //发送到1组1号显示屏，此处需要根据现场情况修改
            #endregion
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
            source.AddHook(WndProc);//add hook to get message  
            Hwnd = source.Handle;
        }
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            IntPtr result = IntPtr.Zero;
            int paramx = wParam.ToInt32();
            string content = "";
            switch (msg)
            {
                case LEDAPI.WM_CREATE:
                    break;
                case LEDAPI.WM_LED_NOTIFY:
                    #region====WM_LED_NOTIFY====
                    PNotifyMessage Notify = new PNotifyMessage();
                    if (LED_GetNotifyMessage(ref Notify) != 0)
                    {
                        switch (Notify.Message)
                        {
                            case LEDAPI.LM_TX_COMPLETE:
                                content = "发送完成";
                                dwLEDStatus["STSTATUS"] = "1";
                                break;
                            case LEDAPI.LM_RESPOND:
                                switch (Notify.Command)
                                {
                                    case LEDAPI.PKC_QUERY:
                                        content = "查询状态成功";
                                        dwLEDStatus["STSTATUS"] = "1";
                                        break;
                                    case LEDAPI.PKC_GET_POWER:
                                        content = (Notify.Status == LEDAPI.LED_POWER_ON) ? "电源已打开" : "电源已关闭";
                                        dwLEDStatus["STPOWER"] = Notify.Status;
                                        break;
                                    case LEDAPI.PKC_SET_POWER:
                                        if (Notify.Result == 99)
                                            content = "处于自动开关屏模式,不能进行电源操作!";
                                        else if (Notify.Status == LEDAPI.LED_POWER_ON)
                                        {
                                            dwLEDStatus["STPOWER"] = "1";
                                            content = "电源已打开";
                                        }
                                        else if (Notify.Status == LEDAPI.LED_POWER_OFF)
                                        {
                                            dwLEDStatus["STPOWER"] = "0";
                                            content = "电源已关闭";
                                        }
                                        break;
                                    case LEDAPI.PKC_GET_BRIGHT:
                                        content = "显示屏亮度为:" + Notify.Status;
                                        dwLEDStatus["STBRIGHT"] = Notify.Status;
                                        break;
                                    case LEDAPI.PKC_SET_BRIGHT:
                                        content = "亮度调整完毕";
                                        dwLEDStatus["STSETBRIGHT"] = "1";
                                        break;
                                    case LEDAPI.PKC_ADJUST_TIME:
                                        content = "时钟校正完成";
                                        dwLEDStatus["STSETCLOCK"] = "1";
                                        break;
                                }
                                break;
                            case LEDAPI.LM_TIMEOUT:
                                content = "传送超时";
                                break;
                        }
                    }
                    #endregion
                    DumpStatusData();
                    break;
                default:
                    break;
            }
            return result;
        }
        private void LoadStatusData()
        {

            filepath = fileroot + @"\LED" + ledkey + @"\LEDStatus.XML";
            if (System.IO.File.Exists(filepath))
            {
                DataSet setResult = new DataSet();
                setResult.ReadXml(filepath);
                setLED = new DataSet();
                setLED.Merge(setResult);
                LEDStatus = setLED.Tables["LEDStatus"];
            }
        }
        public void DumpStatusData()
        {
            try
            {
                filepath = fileroot + @"\LED" + ledkey;
                if (!System.IO.Directory.Exists(filepath))
                {
                    System.IO.Directory.CreateDirectory(filepath);
                }
                filepath = fileroot + @"\LED" + ledkey + @"\LEDStatus.XML";
                if (System.IO.File.Exists(filepath))
                {
                    System.IO.File.Delete(filepath);
                    LEDStatus.WriteXml(filepath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void cmdSaveMaster_Click(object sender, RoutedEventArgs e)
        {

        } 
    }
}
